#include<iostream>
#include<fstream>
#include<string>
#include <sstream>
#include <iomanip>

#include"log.hpp"

using namespace std;

Log::Log() {
	m_level = levelInfo;
	m_modeScreen=0;
	m_modeFile=1;
}
Log::~Log() {
	m_fileStream << "[I]: Log file has been closed" << endl;
	if (m_fileStream.is_open())m_fileStream.close();
}
void Log::setLevel(int level){
	m_level = level;
}
void Log::setModeScreen(int mode){
	m_modeScreen = mode;
}
void Log::setModeFile(int mode){
	m_modeFile = mode;
}

void Log::setFileName(int coreId){
	ostringstream strCoreId;
	strCoreId << setfill('0') << setw(4) << coreId;
	m_fileName = "log_LNS_";
	m_fileName = m_fileName + strCoreId.str();
	m_fileStream.open(m_fileName, ios::out);
}
void Log::welcome(){
	if (m_modeScreen){
		cout << "*************************************" << endl;
		cout << "*          HiFiDi-TDLNS Solve       *" << endl;
		cout << "*        Copyright by CHEN, Chao    *" << endl;
		cout << "*************************************" << endl;
	}
	if (m_modeFile){
		m_fileStream << "******************************************" << endl;
		m_fileStream << "*          HiFiDi-TDLNS Solver           *" << endl;
		m_fileStream << "*        Copyright by CHEN, Chao         *" << endl;
		m_fileStream << "******************************************" << endl;
	}
}
void Log::error(const char* message){
	if (m_level >= levelError) {
		if (m_modeScreen)
			cout << "[E]: " << message << endl;
		if (m_modeFile)
			m_fileStream << "[E]: " << message << endl;
	}
}
void Log::warning(const char* message){
	if (m_level >= levelWarning) {
		if (m_modeScreen)
			cout << "[W]: " << message << endl;
		if (m_modeFile)
			m_fileStream << "[W]: " << message << endl;
	}
}
void Log::info(const char* message){
	if (m_level >= levelInfo) {
		if (m_modeScreen)
			cout << "[I]: " << message << endl;
		if (m_modeFile)
			m_fileStream << "[I]: " << message << endl;
	}
}
void Log::fatalError(const char* message){
	cout << "[FATAL ERROR]: " << message << endl;
	m_fileStream << "[FATAL ERROR]: " << message << endl;
  	exit(EXIT_FAILURE);
}
void Log::errProbe(int ierr,const char* funcName, int lineNum){
	char errInfo[132];
    if (ierr!=0){
        sprintf(errInfo,"error located in %s line %d\n",funcName,lineNum);
		fatalError(errInfo);
    }
}
